package constant.milk.aptprice;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import constant.milk.aptprice.apt.AptSetting;
import constant.milk.aptprice.database.DbAdapter;

public class IntroActivity extends Activity
{
	private static final int APT_VERSION_CODE = 1;
	
	private DbAdapter db;
	
	private Handler mHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			int aptFlag = pref.getInt(getString(R.string.prefAptFlag), 0);
			
			if (aptFlag < APT_VERSION_CODE)
			{
				new ShowDialog().execute(0);
			}
			else 
			{
				startMainActivity();
			}
		}; 
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.intro_activity);
		
		db = DbAdapter.getInstance();
		
		mHandler.sendEmptyMessageDelayed(0, 1000);
	}
	
	private void startMainActivity()
	{
		Intent intent = new Intent(IntroActivity.this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(intent);
		finish();
	}
	
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>
	{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			dialog = new ProgressDialog(IntroActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("집 시세 정보를 셋팅 중입니다. 잠시만 기다려주세요.");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) 
		{
			if (arg0[0] == 0)
			{
				try
				{
					db = DbAdapter.getInstance();
					AptSetting aptSetting = new AptSetting(IntroActivity.this, db);
					aptSetting.setting();
					
					SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);

					SharedPreferences.Editor editor = pref.edit();
					editor.putInt(getString(R.string.prefAptFlag), APT_VERSION_CODE);
					editor.commit();
				} catch (Exception e)
				{
					return 0;
				}
				
				return 0;
			}
			
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) 
		{
			super.onPostExecute(result);

			if (dialog != null) 
			{
				dialog.dismiss();
			}
			
			if (result == 0)
			{
				startMainActivity();
			}
		}
	}
}
